package KylinComponents

import (
	"crypto/md5"
	"encoding/base64"
	"encoding/hex"
	"encoding/json"
	"fmt"
	"github.com/gin-gonic/gin"
)

const TOKEN_EXP = 10000

type UserToken struct {
	UserName string
	UserSalt string
	UserId   string
	TimeStr  string
}

func AuthChecker() gin.HandlerFunc {
	return func(c *gin.Context) {
		token := c.GetHeader("token")
		if token == "" {
			respondWithError(TOKEN_MISSING, c)
			return
		}
		result, _ := Exist(token)
		if result == 0 {
			respondWithError(TOKEN_VALID, c)
			return
		}
		go Expire(token, TOKEN_EXP)
		userToken := TokenDecode(token)
		go c.Set("userToken", userToken)
		c.Next()
	}
}

func AdminChecker() gin.HandlerFunc {
	return func(c *gin.Context) {
		token := c.GetHeader("token")
		if token == "" {
			respondWithError(TOKEN_MISSING, c)
			return
		}
		result := Get(token)
		if result == "" {
			respondWithError(TOKEN_VALID, c)
			return
		}
		c.Next()
	}
}

func respondWithError(code int, c *gin.Context) {
	c.JSON(200, ResultError(code, nil))
	c.Abort()
}

func TokenEncode(token UserToken) string {
	data, _ := json.Marshal(token)
	result, _ := Encode(string(data))
	return result
}

func TokenDecode(token string) UserToken {
	result, _ := Decode(token)
	var userToken UserToken
	err := json.Unmarshal(result, &userToken)
	if err != nil {
		fmt.Println(err)
	}
	return userToken
}
func Password(str string) string {
	if str == "" {
		return ""
	}
	data := base64.StdEncoding.EncodeToString([]byte(str))
	dataByte := md5.New()
	dataByte.Write([]byte(data))
	d1 := hex.EncodeToString(dataByte.Sum(nil))
	return d1
}
